const positionX = 10;
const positionY = 10;
const width = 100;
const height = 100;
const clearCanvasX = 0;
const clearCanvasY = 0;

var g_canvas, g_context, g_rect, g_drag, g_star, g_mouse;

function objectPosition()
{
    g_rect.x = g_mouse.x - g_rect.offsetX;
    g_rect.y = g_mouse.y - g_rect.offsetY;
}

function mouseDown( event )
{
    g_mouse = captureMouse();
    var isMouseInObject = ( g_mouse.x < g_rect.x + g_rect.width ) && ( g_mouse.x > g_rect.x ) && 
                          ( g_mouse.y < g_rect.y + g_rect.height) && ( g_mouse.y > g_rect.y );
    
    if ( isMouseInObject )
    {
        g_drag = true;
        g_rect.offsetX = g_mouse.x - g_rect.x;
        g_rect.offsetY = g_mouse.y - g_rect.y;
        g_canvas.onmousemove = mouseMove;
        g_canvas.onmouseup = mouseUp;
    }
}

function drawFrame( x, y )
{
    g_context.clearRect(clearCanvasX, clearCanvasY, g_canvas.width, g_canvas.height);
    g_rect.x = x;
    g_rect.y = y;     
    g_rect.draw( g_context, positionX, positionY );
}
    

function mouseMove( event )
{
    g_mouse = captureMouse();

    if ( g_drag )
    {           
        objectPosition();
        drawFrame( g_rect.x, g_rect.y );
    }
}

function mouseUp( event )
{
    g_drag = false;
    g_mouse = captureMouse();

    if ( g_drag )
    {           
        objectPosition();
    }
}


function onloadHandler()
{
    g_canvas = document.getElementById('canvas');
    g_context = g_canvas.getContext('2d');
    g_drag = false;
    g_rect = new Rectangle( positionX, positionY, width, height );

    g_rect.draw( g_context, positionX, positionY );
    canvas.onmousedown = mouseDown;
}

window.onload = onloadHandler;    